import { autoLogin, findUser } from '@/apis/userAPI'
import { LoginModel, LonginResponeModel, UserModel } from '@/types/model'
import { ref } from 'vue'

export default () => {
  const loginRespone = ref<LonginResponeModel>()
  const user = ref<UserModel>()
  /**
   * 登录
   * @param value 登录表单数据
   */
  const login = async (value: LoginModel) => {
    const { data } = await autoLogin(value)

    // 存储token到localStorage
    localStorage.setItem('token', data.token)
    // 存储用户id到localStorage
    localStorage.setItem('userId', data.userId.toString())

    loginRespone.value = {
      token: data.token,
      userId: data.userId,
    }
  }

  /**
   * 根据id查询用户信息
   * @param userId 用户id
   */
  const find = async (userId: number) => {
    const { data } = await findUser(userId)
    user.value = data
  }

  return { login, find, loginRespone, user }
}
